<?php
namespace Duobao\Model;

use Think\Model;
use Duobao\Controller\LogController as Mylog;

class ShareorderModel extends Model{
    protected $tableName = 'shaidan';

    /**
     * 所有的晒单
     * 默认商品id为0，判断id为0时：按晒单的方式（页面上的晒单），否则查询当前id的往期晒单
     */
    public function all($id=0,$offset=0,$length=10){
        $shareOrder = new \Think\Model();

        if($id==0) {
            $share = $shareOrder->query("select __PREFIX__shaidan.sd_id,__PREFIX__member.username,__PREFIX__shaidan.sd_title,__PREFIX__shaidan.sd_thumbs,__PREFIX__shaidan.sd_content,__PREFIX__shaidan.sd_time from __PREFIX__shaidan inner join __PREFIX__member ON __PREFIX__shaidan.sd_userid=__PREFIX__member.uid ORDER BY __PREFIX__shaidan.sd_time DESC limit $offset,$length");

            if ($share) {

                $tmp = array();
                foreach ($share as $item) {
                    $tmp['id'] = $item['sd_id'];
                    $tmp['usename'] = $item['username'];
                    $tmp['title'] = $item['sd_title'];
                    $tmp['thumbs'] = C('CDN_DOMAIN').C('UPLOAD_PATH').$item['sd_thumbs'];//晒单的产品的图片（压缩）
                    $tmp['content'] = $item['sd_content'];//晒单的内容
                    $tmp['time'] = date("Y-m-d H:i:s",$item['sd_time']);//晒单时间

                    $list[] = $tmp;
                }
            }
        }else{
            #查询当前商品的往期，获取商品的sid
            $condition['id'] = $id;
            $sid = $shareOrder->table("__SHOPLIST__")->where($condition)->getField('sid');
            $share = $shareOrder->query("select __PREFIX__shaidan.sd_id,__PREFIX__member.username,__PREFIX__shaidan.sd_title,__PREFIX__shaidan.sd_thumbs,__PREFIX__shaidan.sd_content,__PREFIX__shaidan.sd_time from __PREFIX__shaidan inner join __PREFIX__member ON __PREFIX__shaidan.sd_userid=__PREFIX__member.uid WHERE __PREFIX__shaidan.sd_shopsid = $sid ORDER BY __PREFIX__shaidan.sd_qishu DESC limit $offset,$length");

            if ($share) {

                $tmp = array();
                foreach ($share as $item) {
                    $tmp['id'] = $item['sd_id'];
                    $tmp['usename'] = $item['username'];
                    $tmp['title'] = $item['sd_title'];
                    $tmp['thumbs'] = C('CDN_DOMAIN') . C('UPLOAD_PATH') .$item['sd_thumbs'];//晒单的产品的图片（压缩）
                    $tmp['content'] = $item['sd_content'];//晒单的内容
                    $tmp['time'] = date("Y-m-d H:i:s",$item['sd_time']);//晒单时间

                    $list[] = $tmp;
                }
            }
        }
        return $list;
    }

    /**
     * 单品的晒单，根据商品的id返回用户晒单的内容
     */
    public function getShareOrderById($id=''){

        $shareOrder = new \Think\Model();

        $share = $shareOrder->query("select __PREFIX__shaidan.sd_id,__PREFIX__shoplist.title,__PREFIX__shaidan.sd_userid ,__PREFIX__member.username,__PREFIX__shaidan.sd_qishu,__PREFIX__shaidan.sd_ip,__PREFIX__shaidan.sd_title,__PREFIX__shaidan.sd_thumbs,__PREFIX__shaidan.sd_content,__PREFIX__shaidan.sd_photolist,__PREFIX__shaidan.sd_time,__PREFIX__shoplist.q_end_time,__PREFIX__shoplist.q_user_code,__PREFIX__shaidan.sd_shopid ,SUM(__PREFIX__member_go_record.gonumber) as gonumber from __PREFIX__shaidan inner join __PREFIX__member ON __PREFIX__shaidan.sd_userid=__PREFIX__member.uid INNER JOIN __PREFIX__shoplist ON __PREFIX__shaidan.sd_shopid=__PREFIX__shoplist.id INNER JOIN __PREFIX__member_go_record ON __PREFIX__member_go_record.shopid = __PREFIX__shaidan.sd_shopid AND __PREFIX__member_go_record.uid = __PREFIX__shaidan.sd_userid where __PREFIX__shaidan.sd_id=$id GROUP BY __PREFIX__member_go_record.uid " );

       if($share){

           $tmp = array();
           $photolist = array();#分割晒单图片
           foreach($share as $item){
               $tmp['id'] = $item['sd_id'];
               $tmp['goodsname'] = $item['title'];
               $tmp['usename']=$item['username'];
               $tmp['periods']=$item['sd_qishu'];//期数
               $tmp['uid'] = $item['sd_userid'];#晒单用户id
               $tmp['ip']=$item['sd_ip'];//晒单ip
               $tmp['title']=$item['sd_title'];
               $tmp['thumbs']= C('CDN_DOMAIN') . C('UPLOAD_PATH') .$item['sd_thumbs'];//晒单的产品的图片（压缩）
               $tmp['content']=$item['sd_content'];//晒单的内容
               #$tmp['photolist']=$item['sd_photolist'];//图片列表
               $item['sd_photolist'] = explode(';',$item['sd_photolist']);#分割数组
               foreach($item['sd_photolist'] as $val){
                   #去除多余的数组的值
                   if(empty($val)){
                       break;
                   }
                   $photolist[] = C('CDN_DOMAIN') . C('UPLOAD_PATH') .$val;
               }
               $tmp['photolist'] = $photolist;

               $tmp['time']=date("Y-m-d H:i:s",$item['sd_time']);//晒单时间
               $tmp['lucklyNum'] = $item['q_user_code'];//中奖号码
               $tmp['endTime'] = date("Y-m-d H:i:s",$item['q_end_time']);
               $tmp['goodsId'] = $item['sd_shopid'];

               #获取用户购买的次数
//               $condition['shopid'] = $item['shopid'];
//               $condition['uid'] = $item['sd_userid'];
                $tmp['buyNum'] = $item['gonumber'];
               $order[]=$tmp;
           }
       }

        return $order;
    }

    /**
     * 用户添加晒单
     */
    public function setShareOrder($uid,$goodsId,$title,$content,$photolist){
        $model = new \Think\Model();
        #判断用户的uid是否与用户的中奖对应
        $condition['id'] = $goodsId;
        $condition['q_uid'] = $uid;

        #判断商品与中奖用户的id是否对应,通过期数判断，是否存在
        $shoplist = $model->table("__SHOPLIST__")->where($condition)->field('qishu,sid')->find();
        if(!$shoplist){
            return false;
        }
        #Mylog::write($periods);

        $data['sd_userid'] = $uid;
        $data['sd_shopid'] = $goodsId;

        #根据商品id获取商品的期数
        #根据商品id获取商品的期数
//        $condition['id'] = $goodsId;
//        $periods = $model->table('__SHOPLIST__')->where($condition)->getField('qishu');

        $data['sd_qishu'] = $shoplist['qishu'];
        $data['sd_ip'] = $_SERVER["REMOTE_ADDR"];
        $data['sd_title'] = $title;
        $data['sd_content'] = $content;
        $data['sd_time'] = time();
        $data['sd_shopsid'] = $shoplist['sid'];

//        $photolist = explode(';',$photolist);
        $image = new \Think\Image();
        #判断目录是否存在
        $dir = 'shaidan/'.date("Ymd",time())."/";
        $photoPath =C("UPLOAD_IMG").$dir.'/';
        if(!is_dir($photoPath)){
            #如果目录不存在创建目录
            mkdir($photoPath);
        }
        $i = 0;
        $photolist =  json_decode($photolist,true);
        $filename = array();#图片名称数组
        $type = array();#图片类型数组
        foreach($photolist as $item){
            #Mylog::write("foreach");
            $filename[] = time().rand(1,9999).$uid;
            //保存base64字符串为图片
            //匹配出图片的格式
            if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $item, $result)){
                $type[] = $result[2];#获取图片类型
                $new_file = $photoPath.$filename[$i].'.'.$type[$i];#定义文件保存路径和文件名
                $item = explode(',',$item)[1];
                if (file_put_contents($new_file, base64_decode($item))){
                    #Mylog::write('文件保存成功23');
                }else{
                    Mylog::write("晒单文件保存失败");
                }
            }
            $i++;
        }
        #生成压缩图
        #$image->thumb(300, 300)->save($photoPath  . $filename[0] . "_thumb." . $type[0]);

        $data['sd_thumbs'] = $dir.$filename[0].'.'.$type[0];
        $list = '';
        foreach($filename as $key=>$item2){
            $list .= $dir.$item2.".".$type[$key].';';
        }
        $data['sd_photolist'] = $list;

        $result = $model->table('__SHAIDAN__')->add($data);
        return $result;
    }

    /**
     * 用户晒单，获取每个用户的晒单列表
     */
    public function getUserShareByUID($uid,$offset,$length){
        $condition = array();
        $condition['sd_userid'] = $uid;

        $result = $this->field('sd_id,sd_title,sd_time,sd_content,sd_thumbs')->where($condition)->limit($offset,$length)->order('sd_time desc')->select();

        if($result){

            $tmp = array();
            foreach($result as $item){
                $tmp['id'] = $item['sd_id'];#晒单id
                $tmp['title'] = $item['sd_title'];#晒单标题
                $tmp['time'] = date("Y-m-d H:i:s",$item['sd_time']);#晒单时间#
                $tmp['content'] = $item['sd_content'];#晒单内容
                $tmp['thumbs'] = C('CDN_DOMAIN') . C('UPLOAD_PATH').$item['sd_thumbs'];#压缩图

                $list[] = $tmp;
            }
        }

        return $list;
    }

    /* end of share order model*/
}